import os

from flask import Blueprint, jsonify, request, send_file

from app.mappers.EmployeeInfoDao import EmployeeInfoDao
from app.mappers.models import EmployeeInfoSchema, EmployeeInfo

employee_info_controller_bp = Blueprint('employee-info-controller', __name__)
employeeInfoDao = EmployeeInfoDao()


@employee_info_controller_bp.route("/login", methods=["POST"])
def login():
    request_body = request.get_json()
    username = request_body.get("username")
    password = request_body.get("password")

    # 查询用户名和密码匹配的用户信息
    employee_info = employeeInfoDao.findByUsername(username, password)

    if not employee_info:
        # 如果查找不到相应的用户，则返回错误提示
        result_msg = {"code": "401", "msg": "用户名或密码错误"}
    else:
        # 如果查找到了相应的用户，则返回成功信息以及用户信息数据
        result_msg = {"code": "200", "data": employee_info, "msg": "登录成功"}

    return jsonify(result_msg)


@employee_info_controller_bp.route("/find-all", methods=["GET"])
def findAll():
    try:
        employeeInfoDao = EmployeeInfoDao()
        employeeInfo = employeeInfoDao.findAll()
        employeeInfoSchema = EmployeeInfoSchema(many=True)
        employeeInfoData = employeeInfoSchema.dump(employeeInfo)
        resultMsg = {"code": 200, "data": employeeInfoData, "msg": "操作成功"}
    except Exception as e:
        print(e)
        resultMsg = {"code": 500, "msg": "服务器内部错误"}
    return jsonify(resultMsg)


@employee_info_controller_bp.route("/update-one", methods=["POST"])
def updateOne():
    resultMsg = {"code": "200", "msg": "操作成功"}
    request_body = request.get_json()
    id = request_body.get("id")
    # 检查是否包含所有必须的属性
    if not all(k in request_body for k in ["name", "gender", "department_id", "position_id", "contact_number"]):
        resultMsg["code"] = "400"
        resultMsg["msg"] = "请求体中包含不完整的员工信息"
        return jsonify(resultMsg)

    # 从请求体中获取属性值
    name = request_body["name"]
    username = request_body["username"]
    password = request_body["password"]
    gender = request_body["gender"]
    department_id = request_body["department_id"]
    position_id = request_body["position_id"]
    contact_number = request_body["contact_number"]
    photo = request_body.get("photo", "")  # 设置默认值为空字符串

    # 更新员工信息
    flag = employeeInfoDao.updateById(id, username, password, name, gender, department_id, position_id, contact_number,
                                      photo)

    if flag:
        resultMsg["code"] = 200
        resultMsg["msg"] = "操作成功"
    else:
        resultMsg["code"] = 201
        resultMsg["msg"] = "操作失败"

    return jsonify(resultMsg)


@employee_info_controller_bp.route("/add-one", methods=["POST"])
def addOne():
    # 返回值
    resultMsg = {"code": "200", "msg": "操作成功"}
    request_body = request.get_json()
    # id = request_body["id"]
    name = request_body["name"]
    username = request_body["username"]
    password = request_body["password"]
    gender = request_body["gender"]
    # birthday = request_body["birthday"]
    department_id = request_body["department_id"]
    position_id = request_body["position_id"]
    contact_number = request_body["contact_number"]
    role_id = 2
    photo = request_body.get("photo", "")  # 设置默认值为空字符串

    employee = EmployeeInfo(name=name, username=username, password=password, gender=gender, department_id=department_id,
                            position_id=position_id, contact_number=contact_number, photo=photo, role_id=role_id)

    flag = employeeInfoDao.addOne(employee)

    if flag:
        resultMsg["code"] = 200
        resultMsg["msg"] = "操作成功"
    else:
        resultMsg["code"] = 201
        resultMsg["msg"] = "操作失败"

    return jsonify(resultMsg)


@employee_info_controller_bp.route("delete-one", methods=["GET"])
def deleteOne():
    # 返回值
    resultMsg = {"code": "200", "msg": "操作成功"}

    # 从查询参数中获取ID
    id = request.args.get('id')

    # 修改文学类型
    flag = employeeInfoDao.deleteById(id)

    if flag:
        resultMsg["code"] = 200
        resultMsg["msg"] = "操作成功"
    else:
        resultMsg["code"] = 201
        resultMsg["msg"] = "操作失败"

    return jsonify(resultMsg)


@employee_info_controller_bp.route("find-name", methods=["POST"])
def findByname():
    request_body = request.get_json()
    employee_name = request_body.get("employee_name")
    department_id = request_body.get("department_id")
    position_id = request_body.get("position_id")
    result = employeeInfoDao.get_by_conditional(employee_name, department_id, position_id)
    result_msg = {"code": 200, "data": result, "msg": "操作成功"}
    return jsonify(result_msg)


@employee_info_controller_bp.route('/find-id', methods=['GET'])
def findById():
    try:
        id = request.args.get("id")
        employeeInfo = employeeInfoDao.getById(id)
        resultMsg = {"code": 200, "data": employeeInfo, "msg": "操作成功"}
    except Exception as e:
        print(e)
        resultMsg = {"code": 500, "msg": "服务器内部错误"}
    return jsonify(resultMsg)


# 上传图片接口
@employee_info_controller_bp.route('/upload-image', methods=['POST'])
def upload_image():
    file = request.files['file']
    filename = file.filename
    if not os.path.exists('app/resources/photo'):  # 如果目录不存在则创建
        os.makedirs('app/resources/photo')
    file.save(os.path.join('app/resources/photo', filename))
    return jsonify({"code": 200, 'filename': filename, "msg": "上传成功"})


# 获取图片接口
@employee_info_controller_bp.route('/get-image/<filename>', methods=['GET'])
def get_image(filename):
    filepath = os.path.join('resources/photo', filename)
    # if not os.path.isfile(filepath):
    #     return jsonify({"code": 404, "msg": "文件未找到"})
    return send_file(filepath, mimetype='image/jpeg')
